package com.example.zwh.testsocket;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.*;
import java.io.*;
import java.net.Socket;
import java.util.concurrent.*;


public class MainActivity extends AppCompatActivity {
    private EditText editText_input = null;
    private TextView textView_show = null;
    private Socket socket = null;
    private DataOutputStream out = null;
    private DataInputStream in = null;
    private Button button_send = null;
    private Button button_connect = null;

    private ExecutorService mThreadPool;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        button_send = (Button) findViewById(R.id.button_send);
        editText_input = (EditText) findViewById(R.id.editText_input);
        textView_show = (TextView) findViewById(R.id.textView_show);
        mThreadPool = Executors.newCachedThreadPool();
        button_connect = (Button) findViewById(R.id.button_connect);

        button_connect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mThreadPool.execute(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            socket = new Socket("39.108.12.42", 9050);
                            Log.d("MainActivity", "#####: "+socket.isConnected());
                            Toast.makeText(MainActivity.this, "#####: "+socket.isConnected(), Toast.LENGTH_SHORT).show();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
            }
        });

        button_send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mThreadPool.execute(new Runnable() {
                    @Override
                    public void run() {
                        String inputText = editText_input.getText().toString();
                        //Toast.makeText(MainActivity.this, inputText, Toast.LENGTH_SHORT).show();
                        //textView_show.setText(inputText);
                        try {
                            // 发送给服务器的数据
                            out = new DataOutputStream(socket.getOutputStream());
                            out.writeUTF(inputText);
                            // 接收服务器的返回数据
                            in = new DataInputStream(socket.getInputStream());
                            textView_show.setText(in.readUTF());
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
            }
        });
    }
}
